package com.chang.multithread;


import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TwoPhaseTermination {
    private Thread monitor;

    //启动监控线程
    public void start(){
        monitor=new Thread(()->{
            while (true){
                Thread current = Thread.currentThread();
                if (current.isInterrupted()){
                    log.debug("被打断了，准备料理后事吧！");
                    break;
                }
                try {
                    Thread.sleep(1000);//情况1
                    log.debug("执行监控记录！");//情况2
                } catch (InterruptedException e) { //这里出现被打断异常，打断标记需要手动设置为真
                    e.printStackTrace();
                    //重新设置打断标记
                    current.interrupt();
                }
            }
        });
        monitor.start();

    }

    //停止监控线程
    public void stop(){
        monitor.interrupt();
    }

    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination tpt=new TwoPhaseTermination();
        tpt.start();

        Thread.sleep(3500);
        tpt.stop();
    }

}

